<?php
class Geo_City_model extends MY_Model
{
	public
		$table = 'geo_cities',
		$prKey = 'id'
	;
	
	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id' 				=> '',		
			'id_countries'		=> T_('Country'),
			'id_states'			=> T_('State'),
			'id_regions'		=> T_('Region'),
			'name'		 		=> T_('City'),
			'phone_code' 		=> T_('Phone code'),	
		);
		
		$this->rules = array(
			'id_countries'		=> "trim|strip_tags|required|is_natural_no_zero",
			'id_states'			=> "trim|strip_tags|is_natural_no_zero",
			'id_regions'		=> "trim|strip_tags|integer",
			'name' 				=> "trim|strip_tags|required|max_length[64]",
			'phone_code' 		=> "trim|strip_tags|max_length[10]",
		);		
	}
	
	function getSelectOptions($id_state = null, $name_state = null)
	{
		if (!empty($id_state))
		{
			$this->db->where('id_states', $id_state);	
		}
		elseif (!empty($name_state))
		{
			$state = $this->db->query('SELECT id FROM geo_states WHERE name='.$this->db->escape($name_state))->row();
			if (!empty($state->id))
			{
				$this->db->where('id_states', $state->id);
			}
			else
			{
				$this->db->where('id_states', 0);
			}
		}
		else
		{
			return array();
		}
		
		$this->db->order_by('name');
		$query = $this->db->get($this->table);		

		if ($query->num_rows() > 0)
		{
			//$options[0] = T_('-выберите-');
			$options = array();
			foreach ($query->result() as $row)
			{
				$options[$row->id] = $row->name;
			}			
		}
		else
		{
			return array('0' => T_("- No Data -"));
		}

		return $options;
	}
	
	function search($config = array())
	{
		$config = array_merge(array('rowsOnPage' => 5, 'order' => 'id'), $config);
		if ($this->input->post('per_page'))
		{
			$config['rowsOnPage'] = $this->input->post('per_page');
			$per_page = 0;
		}		
		else if ($this->input->get('per_page'))
		{
			$per_page = $this->input->get('per_page');
		}
		else
		{
			$per_page = 0;
		}

		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');
		$search 	= $this->input->get_post('search');
		$id_states  = $this->input->get_post('id_states');
		$id_states_regions = $this->input->get_post('id_states_regions');

		// main sql		
		$sql = '';
		$sql .= ' FROM '.$this->table.' c';
		$sql .= ' 	left join geo_states s on c.id_states=s.id
   					left join geo_countries co on s.id_countries=co.iso_nr ';
		$sql .= ' WHERE 1=1 ';  
			
		if ($search)
		{
			$sql .= ' AND c.name LIKE ' . $this->db->escape('%' . $search . '%'); 
		}
		
		switch ($order)
		{
			default:
				$sql .= ' ORDER BY c.name';
				$direction = 'ASC';
		}
		
		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';

		// pagination config
		$config['base_url'] = Xurl_add(Xregenerate_url('per_page,search', true), 'search', $search);
		$config['per_page'] = $config['rowsOnPage'];
		//$config['total_rows'] = $this->getRowCount($sql);

		//$this->pagination->initialize($config); 
		
		// main sql
		$sql = 'SELECT c.*, s.name AS state_name, co.name AS country_name' . $sql . ' LIMIT 1000';// . sprintf(' LIMIT %d, %d', $per_page, $config['per_page']); 

		$this->data['list'] = $this->db->query($sql)->result();

		$this->data['per_page'] 	= $per_page;
		$this->data['search'] 		= $search;
		$this->data['id_states'] 	= $id_states;
		$this->data['id_states_regions'] = $id_states_regions;  
	}
		
    function search_autocomplete()
    {
    	$query = isset($_GET['query']) ? $_GET['query'] : null;
    	$id_geo_states = $this->input->get_post('id_geo_states');
   		$cities['query'] = $query;
   		$cities['data'] = array();
   		$cities['suggestions'] = array();
   		
   		if (!$id_geo_states)
   		{
   			return false;
   		}
   		
   		$sql = "SELECT id, name 
   				FROM ".$this->table." 
   				WHERE name LIKE ('".$query."%') AND id_states=".$this->db->escape($id_geo_states);
   		$data = $this->db->query($sql)->result();
   		foreach ($data as $item)
   		{
   			$cities['data'][] = $item->id;
   			$cities['suggestions'][] = $item->name;
   		} 

   		return Zend_Json::encode($cities);
    }
    
	function hasDistricts($id_city)
	{
		$sql = 'SELECT COUNT(id) AS num FROM geo_districts WHERE id_cities='. $id_city;
		$result = $this->db->query($sql)->row();
		
		return $result->num;
	}	
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			/*if ($this->geo_city_model->hasDistricts($id) > 0)
			{
				$this->log->writeMessage('error', T('Для этого города заданы его районы. Удаление невозможно.'));
				$report .= ",0"; // don't deleted
			}
			else
			{*/
				//$data = $this->geo_city_model->get($id);
				
				$res = $this->db->delete($this->table, array($this->prKey => $id));	
				
				if (is_null($res))
				{
					$this->log->writeMessage('error', T_('Error. City was not removed.'));
					$report .= ",0"; // don't deleted
				}
				else
				{
					$this->log->writeMessage('done', T_('City was removed.'));
					$report .= ",1"; // deleted
				}
			//}						
		}
		return substr($report, 1);
	}

	function insert($data)
	{
		if (!empty($data))
		{
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('City was added succesfully.'));
				
				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! City was not created.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			$res = parent::update($data);

			$this->log->writeMessage('done', T_('Saved succesfully.'));

			return TRUE;			
		}		
	}	
}
?>